<template>
  <div class="user-management-container">
    <!-- 搜索栏 - 添加卡片阴影和圆角 -->
    <el-card class="search-card" shadow="always" :body-style="{padding: '20px'}">
      <el-row type="flex" align="middle">
        <el-col :span="20">
          <el-input
            v-model="searchModel.username"
            placeholder="用户名"
            clearable
            prefix-icon="el-icon-user"
            class="search-input"
          ></el-input>
          <el-input
            v-model="searchModel.phone"
            placeholder="电话"
            clearable
            prefix-icon="el-icon-phone"
            class="search-input"
            type="tel"
            maxlength="11"
            @input="handleSearchPhoneInput"
          ></el-input>
          <el-button 
            type="primary" 
            icon="el-icon-search" 
            @click="getUserList"
            class="search-btn"
          >查询</el-button>
        </el-col>
        <el-col :span="4" style="text-align: right">
          <el-button 
            @click="openEditUI(null)" 
            type="primary" 
            icon="el-icon-plus"
            class="add-btn"
          >新增用户</el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 结果列表 - 添加悬停效果 -->
    <el-card class="table-card" shadow="always" :body-style="{padding: '0 20px'}">
      <el-table
        :data="userList"
        stripe
        border
        style="width: 100%"
        v-loading="loading"
        element-loading-text="拼命加载中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(255, 255, 255, 0.7)"
        highlight-current-row
        @row-click="handleRowClick"
      >
        <el-table-column label="#" width="80" align="center" fixed>
          <template slot-scope="scope">
            {{
              (searchModel.pageNo - 1) * searchModel.pageSize + scope.$index + 1
            }}
          </template>
        </el-table-column>
        <el-table-column
          prop="id"
          label="用户ID"
          width="180"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="username"
          label="用户名"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="phone"
          label="电话"
          width="180"
          align="center"
        ></el-table-column>
        <el-table-column prop="email" label="电子邮箱"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-tag 
              :type="scope.row.status === 1 ? 'success' : 'danger'"
              effect="dark"
            >
              {{ scope.row.status === 1 ? "启用" : "禁用" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button
            @click="openEditUI(scope.row.id)"
              size="mini"
              type="text"
              icon="el-icon-edit"
              @click.stop="handleEdit(scope.row)"
              class="edit-btn"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click.stop="handleDelete(scope.row.id)"
              class="delete-btn"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页组件 - 添加背景和边距 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="searchModel.pageNo"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="searchModel.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      ></el-pagination>
    </div>

    <!-- 用户信息编辑对话框 - 添加动画效果 -->
    <el-dialog
      :title="title"
      :visible.sync="dialogFormVisible"
      width="600px"
      @close="clearForm"
      :close-on-click-modal="false"
      custom-class="custom-dialog"
      :modal-append-to-body="false"
    >
      <el-form
        :model="userform"
        :rules="rules"
        ref="userForm"
        label-position="right"
        label-width="100px"
        class="user-form"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="userform.username"
            placeholder="请输入用户名"
            prefix-icon="el-icon-user"
            class="form-input"
          ></el-input>
        </el-form-item>
        <el-form-item label="登录密码" prop="password">
          <el-input
            type="password"
            v-model="userform.password"
            placeholder="请输入密码"
            prefix-icon="el-icon-lock"
            show-password
            class="form-input"
          ></el-input>
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
          <el-input
            v-model="userform.phone"
            placeholder="请输入联系电话"
            prefix-icon="el-icon-phone"
            type="tel"
            maxlength="11"
            @input="handlePhoneInput"
            class="form-input"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户状态">
          <el-switch
            v-model="userform.status"
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          ></el-switch>
        </el-form-item>
        <el-form-item label="电子邮件" prop="email">
          <el-input
            v-model="userform.email"
            placeholder="请输入电子邮箱"
            prefix-icon="el-icon-message"
            class="form-input"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false" class="cancel-btn">取 消</el-button>
        <el-button 
          type="primary" 
          @click="saveUser" 
          :loading="submitting"
          class="confirm-btn"
        >确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import userApi from "@/api/userManage";

// 邮箱验证函数
const checkEmail = (rule, value, callback) => {
  if (!value) return callback(new Error("请输入邮箱"));
  const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
  reg.test(value) ? callback() : callback(new Error("邮箱格式错误"));
};

export default {
  data() {
    return {
      submitting: false,
      userform: {
        username: "",
        password: "",
        phone: "",
        email: "",
        status: 1,
      },
      dialogFormVisible: false,
      title: "",
      total: 0,
      searchModel: {
        pageNo: 1,
        pageSize: 10,
        username: "",
        phone: "",
      },
      userList: [],
      loading: false,
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 10, message: "长度在3-10个字符", trigger: "blur" },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 20, message: "长度在6-20个字符", trigger: "blur" },
        ],
        phone: [
          { required: true, message: "请输入电话", trigger: "blur" },
          {
            pattern: /^[0-9]{11}$/,
            message: "请输入11位数字电话",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    handleRowClick(row) {
      // 行点击事件，可以添加细节交互
      console.log('Row clicked:', row);
    },
    
    handlePhoneInput(value) {
      this.userform.phone = value.replace(/[^\d]/g, "").substring(0, 11);
    },

    handleSearchPhoneInput(value) {
      this.searchModel.phone = value.replace(/[^\d]/g, "").substring(0, 11);
    },

    clearForm() {
      this.userform = {
        username: "",
        password: "",
        phone: "",
        email: "",
        status: 1,
      };
      this.$nextTick(() => {
        this.$refs.userForm && this.$refs.userForm.clearValidate();
      });
    },

   openEditUI(id) {
  if (id == null) {
    this.title = "新增用户";
  } else {
    this.title = "修改用户";
    //根据id查询用户信息
    userApi.getUserById(id).then(response => {
      this.userform = response.data;
    });
  }
  
  this.dialogFormVisible = true;
},

    handleEdit(row) {
      this.title = "编辑用户";
      this.userform = JSON.parse(JSON.stringify(row));
      this.dialogFormVisible = true;
    },

    handleDelete(id) {
      this.$confirm("确定要删除该用户吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        customClass: "delete-confirm",
        center: true,
        showClose: false
      })
        .then(() => {
          this.loading = true;
          userApi
            .deleteUser(id)
            .then(() => {
              this.$message({
                message: "删除成功",
                type: "success",
                customClass: "success-message"
              });
              this.getUserList();
            })
            .catch((error) => {
              console.error("删除用户失败:", error);
              this.$message({
                message: "删除用户失败",
                type: "error",
                customClass: "error-message"
              });
            })
            .finally(() => {
              this.loading = false;
            });
        })
        .catch(() => {});
    },

    handleSizeChange(pageSize) {
      this.searchModel.pageSize = pageSize;
      this.getUserList();
    },

    handleCurrentChange(pageNo) {
      this.searchModel.pageNo = pageNo;
      this.getUserList();
    },

    async getUserList() {
      this.loading = true;
      try {
        const response = await userApi.getUserList(this.searchModel);
        this.userList = response.data.rows;
        this.total = response.data.total;
      } catch (error) {
        console.error("获取用户列表失败:", error);
        this.$message({
          message: "获取用户列表失败",
          type: "error",
          customClass: "error-message"
        });
      } finally {
        this.loading = false;
      }
    },

    saveUser() {
      if (!this.$refs.userForm) {
        console.error('表单引用不存在');
        return;
      }
      
      this.$refs.userForm.validate((valid) => {
        if (valid) {
          this.submitting = true;
          const apiMethod = this.userform.id
            ? userApi.updateUser(this.userform)
            : userApi.addUser(this.userform);
            

          apiMethod
            .then((response) => {
              this.$message({
                message: response.message || (this.userform.id ? "修改成功" : "添加成功"),
                type: "success",
                customClass: "success-message"
              });
              this.dialogFormVisible = false;
              this.getUserList();
            })
            .catch((error) => {
              console.error("操作失败:", error);
              this.$message({
                message: error.message || "操作失败",
                type: "error",
                customClass: "error-message"
              });
            })
            .finally(() => {
              this.submitting = false;
            });
        } else {
          this.$message({
            message: "请填写完整的表单信息",
            type: "warning",
            customClass: "warning-message"
          });
        }
      });
    },
  },
  created() {
    this.getUserList();
  },
};
</script>

<style lang="scss" scoped>
.user-management-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);

  .search-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: none;
    background: linear-gradient(145deg, #ffffff, #f0f2f5);
    box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1) !important;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.15) !important;
    }

    .search-input {
      width: 220px;
      margin-right: 15px;
      transition: all 0.3s;

      &:hover {
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
      }

      &:focus-within {
        box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.3);
      }
    }

    .search-btn {
      padding: 10px 20px;
      border-radius: 4px;
      transition: all 0.3s;

      &:hover {
        background-color: #409EFF;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.4);
      }
    }

    .add-btn {
      padding: 10px 20px;
      border-radius: 4px;
      background-color: #67C23A;
      border-color: #67C23A;
      transition: all 0.3s;

      &:hover {
        background-color: #5daf34;
        transform: translateY(-1px);
        box-shadow: 0 2px 8px rgba(103, 194, 58, 0.4);
      }
    }
  }

  .table-card {
    margin-bottom: 20px;
    border-radius: 8px;
    border: none;
    background: linear-gradient(145deg, #ffffff, #f0f2f5);
    box-shadow: 0 4px 12px 0 rgba(0, 0, 0, 0.1) !important;
    transition: all 0.3s ease;

    &:hover {
      box-shadow: 0 6px 16px 0 rgba(0, 0, 0, 0.15) !important;
    }

    ::v-deep .el-table {
      border-radius: 8px;
      overflow: hidden;
      font-size: 14px;

      th {
        background-color: #f8fafc !important;
        color: #333;
        font-weight: 600;
        height: 50px;
      }

      td {
        height: 48px;
      }

      .el-table__row {
        transition: all 0.3s;

        &:hover {
          background-color: #f5f7fa !important;
          transform: translateX(2px);
        }
      }

      .edit-btn {
        color: #409EFF;
        transition: all 0.2s;

        &:hover {
          color: #66b1ff;
          transform: scale(1.05);
        }
      }

      .delete-btn {
        color: #F56C6C;
        transition: all 0.2s;

        &:hover {
          color: #f78989;
          transform: scale(1.05);
        }
      }
    }
  }

  .pagination-container {
    display: flex;
    justify-content: center;
    padding: 20px 0;
    background-color: #fff;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  }
}

.user-form {
  padding: 0 20px;

  .form-input {
    transition: all 0.3s;

    &:hover {
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
    }

    &:focus-within {
      box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.3);
    }
  }
}

.dialog-footer {
  text-align: center;
  padding: 20px 0 0;

  .cancel-btn {
    padding: 10px 24px;
    border-radius: 20px;
    border: 1px solid #dcdfe6;
    transition: all 0.3s;

    &:hover {
      color: #409EFF;
      border-color: #c6e2ff;
      background-color: #ecf5ff;
      transform: translateY(-1px);
    }
  }

  .confirm-btn {
    padding: 10px 24px;
    border-radius: 20px;
    transition: all 0.3s;

    &:hover {
      background-color: #66b1ff;
      transform: translateY(-1px);
      box-shadow: 0 2px 8px rgba(64, 158, 255, 0.4);
    }
  }
}

::v-deep {
  .custom-dialog {
    border-radius: 12px;
    overflow: hidden;
    background: linear-gradient(145deg, #ffffff, #f8fafc);

    .el-dialog__header {
      border-bottom: 1px solid #eee;
      padding: 15px 20px;
      background-color: #f8fafc;
      border-radius: 12px 12px 0 0;

      .el-dialog__title {
        color: #333;
        font-weight: 600;
      }
    }

    .el-dialog__body {
      padding: 30px 20px;
    }

    .el-dialog__footer {
      border-top: 1px solid #eee;
      padding: 15px 20px;
      background-color: #f8fafc;
      border-radius: 0 0 12px 12px;
    }

    .el-input__inner {
      -webkit-user-select: text !important;
      user-select: text !important;
      height: 40px;
      line-height: 40px;
      border-radius: 4px;
    }
  }

  .delete-confirm {
    .el-message-box__header {
      background-color: #fef0f0;
    }
    
    .el-message-box__content {
      padding: 20px;
    }
  }

  .success-message {
    background-color: #f0f9eb;
    border-color: #e1f3d8;
  }

  .error-message {
    background-color: #fef0f0;
    border-color: #fde2e2;
  }

  .warning-message {
    background-color: #fdf6ec;
    border-color: #faecd8;
  }
}
</style>